import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_yn_goods/config/app_config.dart';
import 'package:flutter_yn_goods/config/app_routes.dart';
import 'package:flutter_yn_goods/user/app_user_manager.dart';
import 'package:flutter_yn_goods/utils/http/http_code.dart';
import 'package:flutter_yn_goods/utils/http/http_export.dart';
import 'package:flutter_yn_goods/utils/loading/loading_utils.dart';
import 'package:flutter_yn_goods/utils/log/utils_log.dart';
import 'package:flutter_yn_goods/utils/shared/shared_export.dart';

class Application {
  static final Application _instance = Application._();

  factory Application() => _instance;

  Application._();

  Future initialize() async {
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);

    SystemChrome.setEnabledSystemUIMode(
      SystemUiMode.manual,
      overlays: [SystemUiOverlay.top, SystemUiOverlay.bottom],
    );

    // 系统底部控制栏的颜色
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      systemNavigationBarColor: Colors.black,
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark,
    ));
    await LoadingUtils.setup();
    await SharedStorage().initShareStorage();
    AppUserManager().initDataSource();
    await initialPrivacySDK();
  }

  static String initialRoute() {
    return AppRoutes.launcher;
  }

  static void changeStatusBar(
      {Brightness statusBarIconBrightness = Brightness.dark}) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarIconBrightness: statusBarIconBrightness,
    ));
  }

  /// 错误信息打印
  void logSystemError() {
    FlutterError.onError = (errorDetails) {
      clog(errorDetails, tag: "error", always: true);
    };
    PlatformDispatcher.instance.onError = (error, stack) {
      clog("$error \n ${stack.toString()}", tag: "error", always: true);
      return true;
    };
  }

  Future<void> setupHttp() async {
    await Future.wait([
      AppConfig.setup(),
      // AppLocatio.initialize(),
    ]);
    // await AppConfig.setup();
    // await  AppLocation.initialize();
    // 网络请求需要行为操作的code码处理
    // HttpManage().errorCodeListener = httpErrorCodeListener;/
    // HttpConnectionCheck.checkNetWork();
    HttpManager().errorCodeListener = httpErrorCodeListener;
  }

  Future<void> initialPrivacySDK() async {
    await setupHttp();
    // FlutterDeviceId().getDeviceId();
    // FlutterDeviceId
  }

  void httpErrorCodeListener(int? code) {
    code ??= 0;
    // AppLocation

    if (code == HttpCode.code33000) {
      // AppUserManager().updateToken();
    } else if (code == HttpCode.code33002 ||
        code == HttpCode.code33001 ||
        code == 110002 ||
        code == 500055) {
      AppUserManager().logout();
    }
  }
}
